<template>
  <div class="progress-box">
    <p class="title">{{ index }}：{{ code }}</p>
    <div class="progress-row">
      <div class="progress"><el-progress :percentage="curPercent" /></div>
      <div
        :class="
          curPercent === 0
            ? 'waiting'
            : curPercent === 100
            ? 'success'
            : 'pending'
        "
      >
        {{ tagName }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineProps, ref, watch } from 'vue'
const props = defineProps({
  index: {
    type: String,
    default: ''
  },
  code: {
    type: String,
    default: ''
  },
  percentage: {
    type: Number,
    default: 0
  },
  offset: {
    type: Number,
    default: 1
  },
  closeType: {
    type: Boolean,
    default: false
  }
})
const tagName = ref('等待中...')
const curPercent = ref(props.percentage)
const timer = ref(null)

function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time))
}
function addPercent() {
  if (curPercent.value + props.offset < 101) {
    tagName.value = '正在发布'
    curPercent.value += props.offset
  } else {
    tagName.value = '发布完成'
    curPercent.value = 100
  }
}
const setPercent = () => {
  timer.value = setInterval(() => {
    if (props.percentage === 0) {
      sleep(2000).then(() => {
        addPercent()
      })
    } else {
      addPercent()
    }
  }, 1000)
}
setPercent()

const clearTimer = () => {
  clearInterval(timer.value)
  timer.value = null
  tagName.value = '等待中...'
  curPercent.value = props.percentage
}

watch(
  () => props.closeType,
  () => {
    if (!props.closeType) {
      clearTimer()
    } else {
      setPercent()
    }
  }
)
</script>

<style lang="scss" scoped>
.progress-box {
  width: 100%;
  height: 32px;
  font-size: 12px;
  font-family: Microsoft YaHei;
  color: #5d6c8e;
  .title {
    width: 100%;
    height: 16px;
    line-height: 16px;
    margin-bottom: 6px;
  }
  .progress-row {
    width: 100%;
    height: 16px;
    display: flex;
    line-height: 16px;
    .progress {
      width: 300px;
    }
    .waiting {
      height: 16px;
      line-height: 16px;
      margin-right: 22px;
      background: url(~@@/images/back/waitting-icon.png) no-repeat;
      padding-left: 16px;
      text-align: center;
      margin-left: 22px;
    }
    .success {
      @extend.waiting;
      background: url(~@@/images/back/success-icon.png) no-repeat;
      background-size: 14px 14px;
      background-position-y: center;
    }
    .pending {
      @extend.waiting;
      background: url(~@@/images/back/pedding-icon.png) no-repeat;
      background-size: 14px 14px;
      background-position-y: center;
    }
  }
  :deep(.el-progress-bar__outer) {
    height: 10px !important;
    border-radius: 0px;
    background-color: #e5e5e5;
  }
  :deep(.el-progress-bar__inner) {
    border-radius: 0px;
    background: linear-gradient(90deg, #ff9502 0%, #fdd297 100%);
  }
}
</style>
